
#include "Path.h"

namespace MLoader {

    inline void MakeAbsolutePath(const char* in, char* _out)
    {
        ML_ASSERT(in && _out);
        
        char* ret;
		ret = REAL_PATH(in, _out);
        if(!ret) {
            // preserve the input path, maybe someone else is able to fix
            // the path before it is accessed (e.g. our file system filter)
            strcpy(_out,in);
        }
    }

	const char* Path::CString() const
	{
		return _origin.c_str();
	}

    bool Path::Exists() const
    {
        FILE* file = ::fopen(AbsolutePath().c_str(), "rb");
        if(!file) return false;

        ::fclose(file);
        return true;
    }

    char Path::Separator()
    {
#if defined( _MSC_VER ) || defined( __MINGW32__ )
		return '\\'; 
#else
		return '/';
#endif
    }

    bool Path::Compare(const char* p) const
    {
        if (0 == _origin.compare(p)) return true;
        
        char temp1[PATH_MAX];
        char temp2[PATH_MAX];
        MakeAbsolutePath(_origin.c_str(), temp1);
        MakeAbsolutePath(p, temp2);
        
        return 0 == std::string(temp1).compare(temp2);
    }

    std::string Path::FileName() const
    {
        std::string ret = _origin;
        std::size_t last = ret.find_last_of(Separator());
        if (last != std::string::npos) ret = ret.substr(last + 1);
        return ret;
    }

    std::string Path::CompleteBaseName() const
    {
        std::string ret = FileName();
        std::size_t pos = ret.find_last_of('.');
        if(pos != ret.npos) ret = ret.substr(0, pos);
        return ret;
    }

    std::string Path::Extension() const
    {
        std::string::size_type pos = _origin.find_last_of('.');
        if(pos == std::string::npos) return "";

        std::string ret = _origin.substr(pos+1);
        std::transform(ret.begin(),ret.end(),ret.begin(),::tolower);
        return ret;
    }

	std::string Path::Append(const char* dir) const
	{
		return _origin + std::string(1, Separator()) + std::string(dir);
	}

    std::string Path::AbsolutePath() const
    {
        char temp[PATH_MAX];
        MakeAbsolutePath(_origin.c_str(), temp);

        return &(temp[0]);
    }

    std::string Path::DirectoryPath() const
    {
        std::string ret = AbsolutePath();
        std::size_t last = ret.find_last_of(Separator());
        if (last != std::string::npos) ret = ret.substr(0, last);
        return ret;
    }

} // MLoader
